const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const path = require('path'); 
require('dotenv').config({ path: path.resolve(__dirname, '.env') }); // <--- 修改这一行

// --- 1. 引入 Swagger 相关依赖 ---
const swaggerJsdoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');

const app = express();
const PORT = process.env.PORT || 3001;

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 数据库连接
let isMongoConnected = false;

// MongoDB Atlas 连接配置
const connectDB = async () => {
    try {
        const conn = await mongoose.connect(process.env.DATABASE_URL, {
            serverSelectionTimeoutMS: 5000,
            socketTimeoutMS: 45000,
        });

        console.log(`MongoDB Atlas 连接成功: ${conn.connection.host}`);
        console.log(`数据库名称: ${conn.connection.name}`);
        isMongoConnected = true;

        await mongoose.connection.db.admin().ping();
        console.log("数据库连接测试成功!");

    } catch (error) {
        console.error('MongoDB Atlas 连接失败:', error.message);
        console.log('系统将在无数据库模式下运行，使用模拟数据');
        isMongoConnected = false;
    }
};

// 连接数据库
connectDB();

// 导出连接状态
app.locals.isMongoConnected = () => isMongoConnected;


// --- 2. Swagger 配置 ---
const swaggerOptions = {
    definition: {
        openapi: '3.0.0',
        info: {
            title: '干部授课管理系统 API 文档',
            version: '1.0.0',
            description: '用于管理干部、单位、高校和授课计划的 RESTful API。由 Swagger 自动生成。',
            contact: {
                name: 'API Support',
                email: 'support@example.com',
            },
        },
        servers: [
            {
                url: `http://localhost:${PORT}`,
                description: '本地开发服务器',
            },
        ],
        // 如果您的API需要认证，可以在这里添加
        // components: {
        //   securitySchemes: {
        //     bearerAuth: {
        //       type: 'http',
        //       scheme: 'bearer',
        //       bearerFormat: 'JWT',
        //     }
        //   }
        // },
        // security: [{
        //   bearerAuth: []
        // }]
    },
    // 指向包含 API 注释的路由文件
    apis: ['./src/routes/*.js'],
};

const swaggerSpec = swaggerJsdoc(swaggerOptions);

// --- 3. 设置 Swagger UI 路由 ---
// 将生成的文档部署在 /api-docs 路径下
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));


// 路由
const cadreRoutes = require('./src/routes/cadreRoutes');
const unitRoutes = require('./src/routes/unitRoutes');
const universityRoutes = require('./src/routes/universityRoutes');
const planRoutes = require('./src/routes/planRoutes');
const dashboardRoutes = require('./src/routes/dashboardRoutes');
const exportRoutes = require('./src/routes/export');

app.use('/api/cadres', cadreRoutes);
console.log('干部路由已注册');
app.use('/api/units', unitRoutes);
app.use('/api/universities', universityRoutes);
app.use('/api/plans', planRoutes);
app.use('/api/dashboard', dashboardRoutes);
app.use('/api/export', exportRoutes);

// 健康检查
app.get('/api/health', (req, res) => {
    res.json({
        status: 'OK',
        message: '干部授课管理系统后端服务运行正常',
        timestamp: new Date().toISOString()
    });
});

// 错误处理中间件
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).json({
        error: '服务器内部错误',
        message: process.env.NODE_ENV === 'development' ? err.message : '请联系管理员'
    });
});

// 404 处理
app.use('*', (req, res) => {
    res.status(404).json({ error: '接口不存在' });
});


app.listen(PORT, () => {
    console.log(`服务器运行在端口 ${PORT}`);
    console.log(`健康检查: http://localhost:${PORT}/api/health`);
    console.log(`API 文档: http://localhost:${PORT}/api-docs`); // 新增的日志
    if (process.send) {
        // 向父进程（main.js）发送“准备就绪”的信号
  process.send('BACKEND_READY');
        // （可选）添加一条日志，方便调试
        console.log('[Backend] 已向主进程发送 "BACKEND_READY" 信号。');
 }
});